package com.zzyl.nursing.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 简化版身份证工具类，仅用于计算年龄
 */
public class IdCardUtils {

    /**
     * 根据身份证号码计算年龄
     *
     * @param idCard 18位身份证号码
     * @return 周岁年龄，如果身份证格式错误返回-1
     */
    public static int calculateAge(String idCard) {
        if (idCard == null || !idCard.matches("^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}[0-9Xx]$")) {
            return -1;
        }

        try {
            // 提取出生日期 (格式：yyyyMMdd)
            String birthDateStr = idCard.substring(6, 14);
            Date birthDate = new SimpleDateFormat("yyyyMMdd").parse(birthDateStr);

            // 计算年龄
            Calendar birthCal = Calendar.getInstance();
            birthCal.setTime(birthDate);
            Calendar nowCal = Calendar.getInstance();

            int age = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);
            if (nowCal.get(Calendar.DAY_OF_YEAR) < birthCal.get(Calendar.DAY_OF_YEAR)) {
                age--; // 如果还没过生日，则年龄减1
            }

            return age;
        } catch (ParseException | StringIndexOutOfBoundsException e) {
            return -1; // 解析异常或索引越界，返回-1
        }
    }
}    